<?php

/**
 * This is the model class for table "{{faq}}".
 *
 * The followings are the available columns in table '{{faq}}':
 * @property integer $faqId
 * @property string $faqType
 * @property string $faqQid
 * @property integer $faqModelId
 * @property string $faqTitle
 * @property string $faqContent
 * @property integer $faqStatus
 * @property string $faqUserName
 * @property string $faqUserEmail
 * @property integer $faqMostUseful
 */
class Faq extends CActiveRecord {

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return '{{faq}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('faqModelId, faqBrandId, faqCategoryId, faqTitle, faqContent, faqStatus, faqUserName, faqUserEmail, faqUrl', 'required'),
            array('faqId, faqModelId, faqStatus, faqMostUseful', 'numerical', 'integerOnly' => true),
            array('faqType', 'length', 'max' => 8),
            array('faqQid', 'length', 'max' => 10),
            //array('faqTitle, faqContent, faqUserName, faqUserEmail', 'length', 'max' => 1000),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('faqId, faqType, faqQid, faqModelId, faqTitle, faqContent, faqStatus, faqUserName, faqUserEmail, faqMostUseful, model, faqGlobalType', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'model' => array(self::BELONGS_TO, 'Page', 'faqModelId'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'model' => 'sad',
            'faqId' => 'Faq',
            'faqType' => 'Faq Type',
            'faqQid' => 'Faq Qid',
            'faqModelId' => 'Модель',
            'faqTitle' => 'Вопрос',
            'faqContent' => 'Содержание',
            'faqStatus' => 'Статус',
            'faqUserName' => 'Имя пользователя',
            'faqUserEmail' => 'E-mail пользователя',
            'faqMostUseful' => 'Faq Most Useful',
        );
    }

    function isRead() {
        return $this->faqView;
    }

    public function getModels() {
        $array = array();
        $sql = "SELECT * FROM {{tree}} WHERE \"pageType\" = 'model'";
        $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();
        foreach ($models as $model) {
            $array[$model['pageId']] = $model['pageTitle'];
        }
        return $array;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function searchFAQ() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;
        $criteria->order = '"faqView", "faqId" DESC';
        //$criteria->compare('model.pageTitle', $this->model->pageTitle, true);
        $criteria->compare('"faqId"', $this->faqId);
        $criteria->compare('"faqType"', 'question');
        $criteria->compare('"faqType"', $this->faqType, true);
        $criteria->compare('"faqQid"', $this->faqQid, true);
        $criteria->compare('"faqModelId"', $this->faqModelId);
        $criteria->compare('"faqTitle"', $this->faqTitle, true);
        $criteria->compare('"faqContent"', $this->faqContent, true);
        $criteria->compare('"faqStatus"', $this->faqStatus);
        $criteria->compare('"faqUserName"', $this->faqUserName, true);
        $criteria->compare('"faqUserEmail"', $this->faqUserEmail, true);
        $criteria->compare('"faqMostUseful"', $this->faqMostUseful);
        $criteria->compare('"faqGlobalType"', 'qa');

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    public function searchComment() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;
        $criteria->order = '"faqView", "faqId" DESC';
        //$criteria->compare('model.pageTitle', $this->model->pageTitle, true);
        $criteria->compare('"faqId"', $this->faqId);
        $criteria->compare('"faqType"', 'question');
        $criteria->compare('"faqType"', $this->faqType, true);
        $criteria->compare('"faqQid"', $this->faqQid, true);
        $criteria->compare('"faqModelId"', $this->faqModelId);
        $criteria->compare('"faqTitle"', $this->faqTitle, true);
        $criteria->compare('"faqContent"', $this->faqContent, true);
        $criteria->compare('"faqStatus"', $this->faqStatus);
        $criteria->compare('"faqUserName"', $this->faqUserName, true);
        $criteria->compare('"faqUserEmail"', $this->faqUserEmail, true);
        $criteria->compare('"faqMostUseful"', $this->faqMostUseful);
        $criteria->compare('"faqGlobalType"', 'model');

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
                'pagination' => array('pageSize' => 30)
        ));
    }

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Faq the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function getData($type, $parentID = 0) {
        $c = new CDbCriteria();
        $c->select = '"pageTitle", "pageId"';
        $c->compare('"pageType"', $type);
        $c->compare('"pageParent"', $parentID);
        $models = Page::model()->findAll($c);
        return CHtml::listData($models, 'pageId', 'pageTitle');
    }

    public function beforeSave() {
        if (parent::beforeSave()) {
            $this->faqGlobalType = $this->faqGlobalType == 'model' ? 'model' : 'qa';
            if ($this->isNewRecord) {
                $this->faqCreateDate = time();
                $this->faqType = 'question';
                $url = explode('/', $this->faqUrl);
                if ($url[0] != 'qa')
                    $this->faqUrl = 'qa/' . $this->faqUrl;
            }
            return true;
        }
        return FALSE;
    }

    public function afterSave() {
        parent::afterSave();
        if (isset($_POST['answer'])) {
            $sql = "DELETE FROM {{faq}} WHERE \"faqQid\" = '{$this->faqId}'";
            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
            foreach ($_POST['answer'] as $key => $value) {
                if (!empty($value)) {
                    $best = isset($_POST['best']) && $_POST['best'] == $key ? 1 : 0;
                    $sql = "INSERT INTO {{faq}} (\"faqType\", \"faqQid\", \"faqContent\", \"faqUserName\", \"faqUserEmail\", \"faqMostUseful\", \"faqStatus\") VALUES('answer', '{$this->faqId}', '$value', '{$_POST['name'][$key]}', '{$_POST['email'][$key]}', '$best', '1')";
                    Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
                    mTools::sendMail($this->faqUserEmail, 'Поступил ответ на Ваш вопрос.', 'На сайте добавлен ответ на ваш вопрос, вы можете его посмотреть по адресу <a href="http://mobi03.ru/' . $this->faqUrl . '">http://mobi03.ru/' . $this->faqUrl . '</a>');
                }
            }
        }
        return parent::afterSave();
    }

    protected function afterDelete() {
        parent::afterDelete();
        $sql = "DELETE FROM {{faq}} WHERE \"faqQid\" = '$this->faqId'";
        Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->query();
    }

}
